<template>
    <el-container>
        <el-main class="wrapper">
            <v-breadcrumb v-bind:breadcumb="breadcumb"></v-breadcrumb>
            <section class="panel" :style="{height: mainHeight+'px'}">
                <div class="panel-body">
                    <div class="btn-group" style="margin-bottom: 15px">
                        <el-button @click="create" type="primary" icon="fa fa-plus"
                                   size="small"> 新增
                        </el-button>
                        <el-button @click="list" type="primary" icon="fa fa-refresh"
                                   size="small"> 刷新
                        </el-button>
                        <el-button @click="toggleSelection(tableData,multipleSelection)" type="primary" icon="fa fa-toggle-on"
                                   size="small"> 反选
                        </el-button>
                        <el-button @click="deleteSelection(multipleSelection)" type="primary" icon="fa fa-trash"
                                   size="small"> 批量删除
                        </el-button>
                    </div>
                    <div class="bh-btn-group">
                        <div class="bh-search">
                            <el-input  size="medium" placeholder="请输入视频名称" v-model="search.name" class="input-with-select">
                                <el-button slot="append" icon="el-icon-search" @click="list"></el-button>
                            </el-input>
                        </div>
                        <!--<div class="bh-search" style="width: 140px">-->
                            <!--<el-select size="medium" v-model="search.cate_id" filterable placeholder="请选择分类">-->
                                <!--<el-option label="分类(全部)" :value="null"></el-option>-->
                                <!--<el-option-->
                                        <!--v-for="cate in cates"-->
                                        <!--:key="cate.id"-->
                                        <!--:label="cate.name"-->
                                        <!--:value="cate.id">-->
                                <!--</el-option>-->
                            <!--</el-select>-->
                        <!--</div>-->
                        <div class="bh-search"  style="width: 140px">
                            <el-select size="medium" v-model="search.chanel_id" placeholder="请选择频道">
                                <el-option label="频道(全部)" :value="null"></el-option>
                                <el-option
                                        v-for="channel in chanels"
                                        :key="channel.id"
                                        :label="channel.name"
                                        :value="channel.id">
                                </el-option>
                            </el-select>
                        </div>
                        <div class="bh-search"  style="width: 140px">
                            <el-select size="medium" v-model="search.sort" placeholder="排序">
                                <el-option label="默认排序" :value="null"></el-option>
                                <el-option label="浏览量" :value="1"></el-option>
                                <el-option label="分享量" :value="2"></el-option>
                            </el-select>
                        </div>
                        <div class="bh-search"  style="width: 140px">
                            <el-select size="medium" v-model="search.good" placeholder="精选">
                                <el-option label="精选(全部)" :value="null"></el-option>
                                <el-option label="是" :value="1"></el-option>
                                <el-option label="否" :value="2"></el-option>
                            </el-select>
                        </div>
                        <div class="bh-search"  style="width: 140px">
                            <el-select size="medium" v-model="search.option" placeholder="推荐">
                                <el-option label="推荐(全部)" :value="null"></el-option>
                                <el-option label="是" :value="1"></el-option>
                                <el-option label="否" :value="2"></el-option>
                            </el-select>
                        </div>
                        <!--<div class="bh-search"  style="width: 140px">-->
                            <!--<el-select size="medium" v-model="search.wheel" placeholder="轮播">-->
                                <!--<el-option label="轮播(全部)" :value="null"></el-option>-->
                                <!--<el-option label="是" :value="1"></el-option>-->
                                <!--<el-option label="否" :value="2"></el-option>-->
                            <!--</el-select>-->
                        <!--</div>-->
                        <div class="bh-search"  style="width: 140px">
                            <el-select size="medium" v-model="search.admins" placeholder="管理员">
                                <el-option label="管理员(全部)" :value="null"></el-option>
                                <el-option v-for="adminUser in admins" :key="adminUser.id" :label="adminUser.username" :value="adminUser.id"></el-option>
                            </el-select>
                        </div>
                    </div>
                    <el-table v-loading="loading"
                              element-loading-text="努力加载中..."
                              element-loading-spinner="el-icon-loading"
                              @selection-change="handleSelectionChange"
                              ref="multipleTable"
                              :data="tableData"
                              tooltip-effect="dark"
                              :border="true" style="width: 100%">
                        <el-table-column type="selection" width="35px"></el-table-column>
                        <el-table-column prop="id" label="编号" width="60px"></el-table-column>
                        <el-table-column prop="thumb" label="封面图" width="120px">
                            <template slot-scope="scope">
                                <img :src="scope.row.thumb" style="height: 55px;"/>
                            </template>
                        </el-table-column>
                        <el-table-column prop="title" label="标题"></el-table-column>
                        <el-table-column prop="user.username" label="管理员" width="80px"></el-table-column>
                        <!--<el-table-column prop="cate.name" label="分类" width="120px"></el-table-column>-->
                        <el-table-column prop="chanel_id" label="频道" width="60px">
                            <template slot-scope="scope">{{scope.row.chanel_id | channel(chanels) }}</template>
                        </el-table-column>
                        <el-table-column prop="time" label="时长" width="60px"></el-table-column>
                        <el-table-column prop="view" :label="'浏览量【'+countView+'】'" width="180px"></el-table-column>
                        <el-table-column prop="share" :label="'分享量【'+countShare+'】'" width="180px"></el-table-column>
                        <el-table-column prop="share_count" :label="'有效分享【'+countShareAll+'】'" width="180px"></el-table-column>
                        <!--<el-table-column prop="comment_count" label="评论量" width="80px"></el-table-column>-->
                        <el-table-column prop="status_text" label="状态" width="70px">
                            <template slot-scope="scope">
                                <span v-html="scope.row.status_text"></span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="option_text" label="推荐" width="60px">
                            <template slot-scope="scope">
                                <span v-html="scope.row.option_text"></span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="good_text" label="精选" width="60px">
                            <template slot-scope="scope">
                                <span v-html="scope.row.good_text"></span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="good_text" label="轮播" width="60px">
                            <template slot-scope="scope">
                                <span v-html="scope.row.wheel_text"></span>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="270px">
                            <template slot-scope="scope">
                                <router-link :to="{name:'Comment',params:{commentId:scope.row.id}}">
                                <el-button type="primary" size="mini" icon="fa fa-eye" plain>
                                    评论
                                </el-button>
                                </router-link>
                                <el-button type="primary" size="mini" @click="edit(scope.row)" icon="fa fa-edit" plain>
                                    编辑</el-button>
                                <el-button icon="fa fa-trash"
                                           @click="destory(scope.row)" type="danger" size="mini" plain> 删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="pagination">
                        <div class="pagination-total">共 <em>{{pageData.total}}</em> 个视频</div>
                        <el-pagination  v-if="!loading && pageData && pageData.last_page > 1" background layout="prev, pager, next, jumper"
                                       :page-size="pageData.per_page"
                                       :total="pageData.total" :current-page="pageData.current_page"
                                       @current-change="handleCurrentChange">
                        </el-pagination>
                    </div>
                </div>
            </section>
        </el-main>
        <!-- 新增视频分类 -->
        <!-- 新增用户 -->
        <el-dialog
                :title="updateDialogTile"
                custom-class="bh-dialog"
                top="1vh"
                @open="resetForm('dialogForm')"
                :visible.sync="updateDialog"
                width="1000px">

                <el-form :model="formData" size="medium" :status-icon="true" :rules="rules" ref="dialogForm" label-width="80px" class="demo-ruleForm">
                    <el-form-item></el-form-item>
                    <el-form-item required label="标题：" prop="title">
                        <el-input v-model="formData.title"  placeholder="请填写视频标题"></el-input>
                    </el-form-item>
                    <el-form-item required label="链接：" prop="link">
                        <el-input v-model="formData.link" placeholder="请填写视频链接地址"></el-input>
                    </el-form-item>
                    <el-row :gutter="20">
                        <el-col :span="16"><el-form-item required label="封面图：" prop="thumb">
                            <el-row :gutter="20">
                                <div style="position:absolute;z-index:999;margin-top:225px;color:red;">------------裁--剪--线-------------------------------------------------------------------------------------</div>
                                <el-col :span="4" style="text-align: left">
                                    <label class="btn btn-label" for="uploads">上传</label>
                                    <input type="file" id="uploads" style="clip:rect(0 0 0 0);" accept="image/png, image/jpeg, image/gif, image/jpg" @change="uploadImg($event, 1)">
                                    <label class="btn btn-label" @click="rotateLeft">旋转</label>
                                    <label class="btn btn-label" @click="finish('blob')">提交</label>
                                </el-col>
                                <el-col :span="18">
                                    <div class="show-preview" :style="{'border': '1px dashed #ccc','width': '360px', 'height': '288px',  'overflow': 'hidden', 'margin': '5px', 'margin-left': '68px'}">
                                        <div :style="previews.div" class="preview">
                                            <img :src="previews.url" :style="previews.img">
                                        </div>
                                    </div>
                                </el-col>
                                <el-col :span="24">
                                    <div style="width: 100%;height: 340px;border: 1px dashed #ccc;margin-top: 5px">
                                        <vueCropper
                                                ref="cropper"
                                                :img="formData.thumb"
                                                :outputSize="option.size"
                                                :outputType="option.outputType"
                                                :info="true"
                                                :full="option.full"
                                                :canMove="option.canMove"
                                                :autoCrop="option.autoCrop"
                                                :autoCropWidth="option.autoCropWidth"
                                                :autoCropHeight="option.autoCropHeight"
                                                :canMoveBox="option.canMoveBox"
                                                :fixedBox="option.fixedBox"
                                                :original="option.original"
                                                @realTime="realTime">
                                        </vueCropper>
                                    </div>
                                </el-col>
                            </el-row>
                        </el-form-item></el-col>
                        <el-col :span="8">
                            <!--<el-form-item label="人气："  prop="view">-->
                            <!--<el-input v-model="formData.view" placeholder="人气，可不填，默认为0 "></el-input>-->
                            <!--</el-form-item>-->
                            <el-form-item required label="推荐：" prop="option">
                                <el-radio-group v-model="formData.option">
                                    <el-radio border :label="0">不推荐</el-radio>
                                    <el-radio border :label="1">推荐</el-radio>
                                </el-radio-group>
                            </el-form-item>
                            <!--<el-form-item required label="精选：" prop="good">-->
                            <!--<el-radio-group v-model="formData.good">-->
                            <!--<el-radio border :label="0">否</el-radio>-->
                            <!--<el-radio border :label="1">是</el-radio>-->
                            <!--</el-radio-group>-->
                            <!--</el-form-item>-->
                            <el-form-item required label="轮播：" prop="wheel">
                                <el-radio-group v-model="formData.wheel">
                                    <el-radio border :label="0">否</el-radio>
                                    <el-radio border :label="1">是</el-radio>
                                </el-radio-group>
                            </el-form-item>
                            <!--<el-form-item required label="分类："  prop="cate_id">-->
                            <!--<template>-->
                            <!--<el-select v-model="formData.cate_id" filterable placeholder="请选择分类">-->
                            <!--<el-option-->
                            <!--v-for="cate in cates"-->
                            <!--:key="cate.id"-->
                            <!--:label="cate.name"-->
                            <!--:value="cate.id">-->
                            <!--</el-option>-->
                            <!--</el-select>-->
                            <!--</template>-->
                            <!--</el-form-item>-->
                            <el-form-item required label="频道："  prop="chanel_id">
                                <template>
                                    <el-select v-model="formData.chanel_id" placeholder="请选择频道">
                                        <el-option
                                                v-for="channel in chanels"
                                                :key="channel.id"
                                                :label="channel.name"
                                                :value="channel.id">
                                        </el-option>
                                    </el-select>
                                </template>
                            </el-form-item>
                            <el-form-item></el-form-item>
                            <el-button @click="updateDialog = false" style="margin-left:100px;">取 消</el-button>
                            <el-button type="primary" @click="update('dialogForm')">确 定</el-button>
                        </el-col>
                    </el-row>
                </el-form>
                <span slot="footer" class="dialog-footer">

          </span>
        </el-dialog>
    </el-container>
</template>
<script>
    import {mapGetters} from 'vuex';
    import vBreadcrumb from '../layout/breadcrumb.vue';
    import {VideoList,VideoDestory,VideoUpdate,CateAll,VideoDestoryAll} from '../../utils/axios';
    import { VueCropper }  from 'vue-cropper';
    export default {
        components:{vBreadcrumb,VueCropper},
        data(){
            return {
                breadcumb:[{name: "视频管理"}],
                updateDialogTile:'',
                tableData:[],//列表数据
                pageData:[],//分页数据
                cates: [],
                updateDialog:false,
                chanels: [{id:1,name:'美食'},{id:2,name:'情歌'},{id:3,name:'搞笑'},{id:4,name:'祝福'}],
                search: {name: null,page:null,cate_id:null,chanel_id:null,sort:null,good:null,option:null,wheel:null,admins:null},//筛选
                previews: {},
                option: {
                    size: 1,
                    full: false,
                    outputType: 'png',
                    canMove: true,
                    fixedBox: true,
                    autoCrop: true,
                    autoCropWidth: 360,
                    autoCropHeight: 288,
                    original: false,
                    canMoveBox: true
                },
                //用户表单
                formData:{id:'',title: '', thumb: '', link: '',option:0,cate_id:'',chanel_id:'',good:0,wheel:0},
                rules: {
                    title: [{ required: true, message: '请填写视频标题', trigger: 'blur' },],
                    thumb: [{ required: true, message: '请填写视频封面图链接地址', trigger: 'blur' },],
                    link: [{ required: true, message: '请填写视频链接地址', trigger: 'blur' },],
                    cate_id: [{ required: true, message: '请选择分类', trigger: 'blur' },],
                    chanel_id: [{ required: true, message: '请选择频道', trigger: 'change' },],
                },
                multipleSelection: [],
                //统计浏览量
                countView:0,
                //统计分享量
                countShare:0,
                //统计有效分享量
                countShareAll:0,
                admins:[],
            }
        },
        activated(){
            this.$store.dispatch('setActive', '/main');
            this.list();
            this.previews =  {};
            CateAll().then((res)=>{
                this.cates = res.data;
            })
        },
        computed: {
            ...mapGetters(['active','mainHeight','loading','upload']),
            myHeaders(){
                var token = this.$storage.get('token');
                return {
                    Authorization:token.token_type+' ' + token.access_token,
                    Accept:'application/json'
                }
            },
        },
        methods:{
            //分页
            handleCurrentChange(val) {
                this.search.page = val;
                this.list();
            },
            //获取列表
            list(){
                this.$store.dispatch('setLoading', true);
                VideoList({params: this.search}).then((response)=>{
                    if (response.code) {
                        this.$message.error(response.msg);
                    } else {
                        this.$store.dispatch('setLoading', false);
                        this.tableData = response.data.data;
                        this.pageData = response.data;
                        this.countView = response.msg.count.view;
                        this.countShare = response.msg.count.share;
                        this.countShareAll = response.msg.count.share_all;
                        this.admins = response.msg.admins;
                    }
                })
            },
            //编辑
            create(){
                this.formData = {id:'',title: '', thumb: '', link: '',option:1,cate_id:'',chanel_id:'',good:0,wheel:0};
                this.updateDialog = true;
                this.updateDialogTile = '新增视频';
            },
            //编辑
            edit(info){
                this.formData = {
                    id: info.id,
                    title: info.title,
                    thumb: info.thumb,
                    link: info.link,
                    option:info.option,
                    cate_id:info.cate_id,
                    chanel_id:info.chanel_id,
                    good:info.good,
                    wheel:info.wheel
                };
                this.updateDialogTile = '编辑视频';
                this.updateDialog = true;
            },
            //更新
            update(formName){
                if(this.formData.thumb.indexOf('blob:') != -1){
                    this.$message.error('请上传裁剪图片');
                    return false;
                }
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        VideoUpdate(this.formData).then((response)=>{
                            if(response.code){
                                this.$message.error(response.msg);
                            }else{
                                this.$message({
                                    type: 'success',
                                    duration: '1000',
                                    message: response.msg,
                                    onClose:() =>{
                                        this.updateDialog = false;
                                        this.list();
                                    }
                                });
                            }
                        });
                    }
                });
            },
            //删除
            destory(info){
                this.$confirm('确定要删除该视频信息吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    VideoDestory({params:{id: info.id}}).then((response) => {
                        if (response.code) {
                            this.$message.error(response.msg);
                        } else {
                            this.list();
                        }
                    });
                }).catch(() => {});
            },
            //重置表单
            resetForm(formName) {
                if (this.$refs[formName]!==undefined) {
                    this.$refs[formName].resetFields();
                }
            },
            realTime (data) {
                this.previews = data
            },
            rotateLeft() {
                this.$refs.cropper.rotateLeft();
            },
            uploadImg (e) {
                var file = e.target.files[0];
                if (!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(e.target.value)) {
                    this.$message.error('图片类型必须是.gif,jpeg,jpg,png中的一种');
                    return false;
                }
                var reader = new FileReader();
                reader.onload = (e) => {
                    let data;
                    if (typeof e.target.result === 'object') {
                        // 把Array Buffer转化为blob 如果是base64不需要
                        data = window.URL.createObjectURL(new Blob([e.target.result]))
                    } else {
                        data = e.target.result;
                    }
                    this.formData.thumb = data;
                }
                // 转化为blob
                reader.readAsArrayBuffer(file);
            },
            finish(){
                let formData = new FormData();
                this.$refs.cropper.getCropBlob((data) => {
                    let token = this.$storage.get('token');
                    formData.append("pic", data, this.formData.thumb);
                    this.$axios.post(this.upload, formData, {
                        headers:{
                            'Authorization':token.token_type+' ' + token.access_token,
                            'Accept':'application/json'
                        }
                    }).then((response)=>{
                        this.formData.thumb = response.data.data.path;
                    });
                })
            },
            //选择
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            //反选
            toggleSelection(rows,selects){
                let rowsSet = new Set(rows);
                let selectsSet = new Set(selects);
                // 差集
                let differenceNew = Array.from(new Set(rows.concat(selects).filter(v => rowsSet.has(v) && !selectsSet.has(v))));
                this.$refs.multipleTable.clearSelection();
                differenceNew.forEach(row => {
                    this.$refs.multipleTable.toggleRowSelection(row);
                });
            },
            //批量删除
            deleteSelection(selects){
                var that = this;
                this.$confirm('此操作将永久删除选中行, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    var ids = [];
                    for(var i=0;selects.length>i;i++){
                        ids.push(selects[i].id);
                    }
                    VideoDestoryAll({
                        params:{data:ids}
                    }).then((response) => {
                        if (response.code) {
                            this.$message.error(response.msg);
                        } else {
                            this.list();
                            that.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                        }
                    });
                }).catch(() => {});
            },
        },
        filters: {
            channel: function (val,data) {
                if (!val) return '';
                let name = '';
                data.filter((item)=>{
                    if(item.id === val){
                        name = item.name;
                    }
                });
                return name;
            }
        }
    }
</script>
